/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package invitation;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.mail.internet.MimeMessage;
import mail.sendInvitation;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;
/**
 *
 * @author tomasz
 */
@Controller
public class SendInvitation {
 
    private JavaMailSender mailSender;
   
    private VelocityEngine velocityEngine;

    @Autowired
   public void setMailSender(JavaMailSender mailSender) {
      this.mailSender = mailSender;
   }

   @Autowired
   public void setVelocityEngine(VelocityEngine velocityEngine) {
      this.velocityEngine = velocityEngine;
   }
    
    
    
    
    private dao.Firma firma;
    
    @Autowired
    public void setFirma(dao.Firma firma){
        this.firma = firma;
    }
    
    
    @RequestMapping("/send/invitation.htm/{id}")
    public String ViewInvitation(ModelMap model_map, @PathVariable Integer id)
    {
        
         final model.Firma firma = this.firma.findFirmaId(id);
        
                MimeMessagePreparator preparator = new MimeMessagePreparator() {
                 public void prepare(MimeMessage mimeMessage) throws Exception {
                     
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    
                    message.setSubject("Poszło");
                    message.setTo(firma.getEmail());
                    message.setFrom("apap001@wp.pl"); // could be parameterized...
                    
                    
                 
                    Map model = new HashMap();
                    model.Account acc = (model.Account) firma.getAccounts().iterator().next();
                    model.put("datestartfirma", acc.getContent().getDescription());
                    model.put("note", acc.getNote());
                    model.put("firma", firma);
                    
                    String text = VelocityEngineUtils.mergeTemplateIntoString(
                                            velocityEngine, "/invitation.vm", model);
                    
                    message.setText(text, true);
                    
                 }
         };

      
         this.mailSender.send(preparator);
        
        return "invitation/view_invitation";
        
    }
    
    
    
    

    
}
